package com.cooper.scraper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.util.Log;

import com.cooper.android.comm.Resource;
import com.cooper.scraper.DownloadException;
import com.cooper.scraper.ResourceScraper;
import com.cooper.scraper.ResultUrl;
import com.cooper.scraper.ScraperException;

public class SearchResourceCollector<T extends Resource> extends ResourceCollector<T> {

	private static final String SEARCH_LIST_KEY = "SEARCH_LIST_";

	private String keyword;

	public SearchResourceCollector(String keyword) {
		super();
		this.keyword = keyword;
	}

	public String getEncodeKeyword() {
		try {
			return URLEncoder.encode(keyword, "gb2312");
		} catch (UnsupportedEncodingException e) {
			Log.e("SearchResultBooks.getEncodeKeyword", e.getMessage(), e);
			return null;
		}
	}

	@Override
	public String generateKey() {
		return SEARCH_LIST_KEY + getEncodeKeyword() + "_" + getPageNumber();
	}

	@Override
	public ResultUrl scraperListUrl(ResourceScraper<T> scraper)
			throws ScraperException, DownloadException {
		return scraper.createSearchUrl(getEncodeKeyword(), getPageNumber());
	}

	@Override
	public void scraperResult(ResourceScraper<T> scraper, String page)
			throws ScraperException, DownloadException {
		medias = scraper.extractSearchResource(page);
		Log.d("SearchResultMedias", "count:" + medias.size());
		setPageCount(scraper.getSearchPageCount(page));
	}

	@Override
	public boolean subscribed(String key) {
		return key.startsWith(SEARCH_LIST_KEY + getEncodeKeyword() + "_");
	}

	@Override
	public void scraperResult(ResourceScraper<T> scraper, String page,
			String redirectUrl) throws ScraperException, DownloadException {
		medias = scraper.extractSearchResource(page, redirectUrl);
		Log.d("SearchResultMedias", "count:" + medias.size());
		setPageCount(scraper.getSearchPageCount(page, redirectUrl));

	}

}
